package cn.jasonone.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.jasonone.bean.SysRole;
import cn.jasonone.mapper.SysRoleMapper;
import cn.jasonone.service.SysResourceService;
import cn.jasonone.service.SysRoleService;

@Service
public class SysRoleServiceImpl implements SysRoleService {
	@Resource
	private SysRoleMapper sysRoleMapper;
	@Resource
	private SysResourceService resourceService;
	@Value("${roleAdmin:ADMINISTRATOR}")
	private String roleAdmin;

	@Transactional
	@Override
	public boolean save(SysRole sysRole, int[] resourceIds) {
		sysRoleMapper.save(sysRole);
		resourceService.bindRole(sysRole.getId(), resourceIds);
		return true;
	}

	@Override
	public boolean deleteByIds(int... ids) {
		return sysRoleMapper.deleteByIds(ids) > 0;
	}

	@Override
	public List<SysRole> findAll(SysRole sysRole) {
		return sysRoleMapper.findAll(sysRole);
	}

	@Override
	public SysRole findById(int id) {
		return sysRoleMapper.findById(id);
	}

	@Override
	public List<SysRole> findByUserId(int userId) {
		return sysRoleMapper.findByUserId(userId);
	}

	@Transactional
	@Override
	public boolean bindUser(int userId, int[] roleIds) {
		if (isAdmin(userId)) {
			return true;
		}
		// 清除原有关系
		sysRoleMapper.deleteRoleBind(userId);
		// 绑定新的关系
		sysRoleMapper.addRoleBind(userId, roleIds);
		return true;
	}

	@Override
	public boolean isAdmin(int userId) {
		List<SysRole> roles = findByUserId(userId);
		if (roles != null) {
			for (SysRole sysRole : roles) {
				if (roleAdmin.equals(sysRole.getCode())) {
					return true;
				}
			}
		}
		return false;
	}

}
